package com.liuceng.zen.common.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerMapping;

/**
 *
 */
public class RequestUtils {


  /**
   * 获取请求路径
   *
   * @param request
   * @return /url/1
   */
  public static String getRestURL(HttpServletRequest request) {
    return (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
  }

  /**
   * 获取请求路径表达式
   *
   * @param request
   * @return /url/{id}
   */
  public static String getRestPatternURL(HttpServletRequest request) {
    return (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
  }

  /**
   * Convenience method to set a cookie
   *
   * @param response the current response
   * @param name the name of the cookie
   * @param value the value of the cookie
   * @param path the path to set it on
   */
  public static void setCookie(HttpServletResponse response, String name, String value, String path,
      int expiry) {
    /*
     * Set-Cookie: <name>=<value>[; <Max-Age>=<age>] [; expires=<date>][; domain=<domain_name>] [;
     * path=<some_path>][; secure][; HttpOnly]
     */
    Cookie cookie = new Cookie(name, value);
    cookie.setSecure(false);
    cookie.setPath(path);
    cookie.setMaxAge(expiry);
    // cookie.setMaxAge(AppConstants.HOUR * 24 * 30); // 30 days

    response.addCookie(cookie);
  }

  /**
   * Convenience method to get a cookie by name
   *
   * @param request the current request
   * @param name the name of the cookie to find
   * @return the cookie (if found), null if not found
   */
  public static Cookie getCookie(HttpServletRequest request, String name) {
    Cookie[] cookies = request.getCookies();
    Cookie returnCookie = null;
    if (cookies == null) {
      return returnCookie;
    }

    for (final Cookie thisCookie : cookies) {
      if (thisCookie.getName().equals(name) && !"".equals(thisCookie.getValue())) {
        returnCookie = thisCookie;
        break;
      }
    }

    return returnCookie;
  }

  /**
   * Convenience method for deleting a cookie by name
   *
   * @param response the current web response
   * @param cookie the cookie to delete
   * @param path the path on which the cookie was set (i.e. /appfuse)
   */
  public static void deleteCookie(HttpServletResponse response, Cookie cookie, String path) {
    if (cookie != null) {
      // Delete the cookie by setting its maximum age to zero
      cookie.setMaxAge(0);
      cookie.setPath(path);
      response.addCookie(cookie);
    }
  }


}
